package com.jpyl.jpMedicalTreatment.view.activity.product;


import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;

import com.forxindu.kit.box.JavaKit;
import com.jpyl.jpMedicalTreatment.R;
import com.jpyl.jpMedicalTreatment.model.ErrorMessageModel;
import com.jpyl.jpMedicalTreatment.model.ProductsMessageModel;
import com.jpyl.jpMedicalTreatment.model.ResponseModel;
import com.jpyl.jpMedicalTreatment.model.RowsModel;
import com.jpyl.jpMedicalTreatment.model.RowsPeripheralModel;
import com.jpyl.jpMedicalTreatment.model.RxSpf_UserModel;
import com.jpyl.jpMedicalTreatment.network.Const;
import com.jpyl.jpMedicalTreatment.network.Network;
import com.jpyl.jpMedicalTreatment.network.api.ApiError;
import com.jpyl.jpMedicalTreatment.network.api.RequestApi;
import com.jpyl.jpMedicalTreatment.util.StringUtil;
import com.jpyl.jpMedicalTreatment.view.activity.BaseActivity;
import com.jpyl.jpMedicalTreatment.view.activity.news.NewDetailsActivity;
import com.jpyl.jpMedicalTreatment.view.widget.sortlistview.MyBuyPopwindow;
import com.youth.banner.Banner;
import com.youth.banner.listener.OnBannerListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;


/**
 * 产品详情界面
 * banner参考链接https://blog.csdn.net/life_s/article/details/80610770
 * Created by 15697 on 2019/2/28.
 */

public class ProductDetailsActivity extends BaseActivity {

    @BindView(R.id.banner_productDetail)
    Banner bannerProductDetail;
    @BindView(R.id.img_productDetail)
    ImageView imgProductDetail;
    @BindView(R.id.btn_productDetail)
    Button btn_productDetail;

    MyBuyPopwindow buyPopwindow;
    ProductsMessageModel.ProductsModel bean;
    RxSpf_UserModel spfUserModel;
    private List<RowsModel> rowsModelList;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_product_detail;
    }

    @Override
    public void afterCreate(Bundle savedInstanceState) {
        spfUserModel = RxSpf_UserModel.create(this);
        //患者和代理可见购买按钮
        if (spfUserModel.type().get().equals("1")||spfUserModel.type().get().equals("3")) {
            btn_productDetail.setVisibility(View.VISIBLE);
        } else {
            btn_productDetail.setVisibility(View.GONE);
        }
        bean = (ProductsMessageModel.ProductsModel) getIntent().getSerializableExtra("name");
        mTitleTv.setText(bean.getName());
        showPicture();
        bannerProductDetail.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                String url = rowsModelList.get(position).getAdsurl();
                //代码实现跳转
//                Intent intent = new Intent();
//                intent.setAction("android.intent.action.VIEW");
//                Uri content_url = Uri.parse(url);//此处填链接
//                intent.setData(content_url);
//                startActivity(intent);
                startActivity(new Intent(getApplicationContext(), NewDetailsActivity.class)
                        .putExtra("url",
                        url).putExtra("name", "广告"));
            }
        });
        GetAds();
    }

    @OnClick(R.id.btn_productDetail)
    public void onClick() {
        buyPopwindow = new MyBuyPopwindow(ProductDetailsActivity.this, bean.getName(), bean
                .getPrice(), spfUserModel.address().get());
        buyPopwindow.showAtLocation(getLayoutInflater().inflate(R.layout
                        .activity_product_detail, null),
                Gravity.CENTER, 0, 0);
        StringUtil.backgroundAlpha(this, 0.5f);
        buyPopwindow.setOnDismissListener(new popupDismissListener());
        buyPopwindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        buyPopwindow.setCallBack(new MyBuyPopwindow.MyBuyPopwindowListener() {
            @Override
            public void btnSubmit(String count, String address) {
                buyPopwindow.dismiss();
                startActivity(new Intent(getApplicationContext(), ConfirmOrderActivity.class)
                        .putExtra("price", bean.getPrice()).putExtra("count", count).putExtra
                                ("name", bean.getName()).putExtra("proId", bean.getId()).putExtra
                                ("address", address));
            }
        });
    }

    /**
     * 添加新笔记时弹出的popWin关闭的事件，主要是为了将背景透明度改回来
     */
    class popupDismissListener implements PopupWindow.OnDismissListener {
        @Override
        public void onDismiss() {
            StringUtil.backgroundAlpha(ProductDetailsActivity.this, 1f);
        }
    }

    final RequestApi publicApi = Network.getRequestApi();

    //获得广告
    void GetAds() {
        publicApi.jpylGetAds().map(new Func1<ResponseModel<RowsPeripheralModel>,
                RowsPeripheralModel>() {
            @Override
            public RowsPeripheralModel call(ResponseModel<RowsPeripheralModel> responseModel) {
                if (responseModel.getCode() != 0) {
                    ErrorMessageModel messageModel = new ErrorMessageModel(responseModel.getMsg());
                    throw new ApiError(messageModel);
                }
                return responseModel.getData();
            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<RowsPeripheralModel>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
//                        e.printStackTrace();
                        if (e instanceof ApiError) {
                            ApiError error = (ApiError) e;
                        }
                    }

                    @Override
                    public void onNext(RowsPeripheralModel model) {
                        if (!JavaKit.isListEmpty(model.getRows())) {
                            rowsModelList = new ArrayList<>();
                            rowsModelList.addAll(model.getRows());
                            List<String> urlList = new ArrayList<>();
                            for (RowsModel rowsModel : rowsModelList) {
                                urlList.add(rowsModel.getPicurl());
                            }
                            StringUtil.setBannerStyle(bannerProductDetail, urlList);
                        }
                    }
                });
    }

    private void showPicture() {
        switch (bean.getName()) {
            // requestCode即所声明的权限获取码，在checkSelfPermission时传入
            case "艾尔贝清":
                imgProductDetail.setBackgroundResource(R.drawable.image_01);
                break;
            case "珍宫夫":
                imgProductDetail.setBackgroundResource(R.drawable.image_02);
                break;
            case "愈伤带":
                imgProductDetail.setBackgroundResource(R.drawable.image_04);
                break;
            case "劲络通":
                imgProductDetail.setBackgroundResource(R.drawable.image_03);
                break;
            case "ELOCK":
                imgProductDetail.setBackgroundResource(R.drawable.image_05);
                break;
            default:
                break;
        }

    }
}
